<template>
  <div class="filter-tags">
    <el-check-tag
      v-if="hasAll"
      type="primary"
      v-bind="tagConfig"
      :checked="isAllChecked"
      :disabled="disabled"
      @change="toggleAll"
    >
      全部
    </el-check-tag>
    <el-check-tag
      v-for="tag in tagList"
      :key="tag.id"
      type="success"
      v-bind="tagConfig"
      :disabled="disabled"
      :checked="selectedTags.includes(tag.value)"
      @change="toggleTag(tag.value)"
    >
      {{ tag.label }}
    </el-check-tag>
  </div>
</template>
<script setup>
const emit = defineEmits(["changeTag", "update:modelValue", "update:isAllChecked"]);
const props = defineProps({
  disabled: {
    type: Boolean,
    default: false,
  },
  // 标签配置
  tagConfig: {
    type: Object,
    default: () => {},
  },
  modelValue: {
    type: Array,
    default: () => [],
  },
  // 默认单选，可以多选
  isMultiple: {
    type: Boolean,
    default: true,
  },
  // 如果有全部这个选项
  hasAll: {
    type: Boolean,
    default: false,
  },
  tagList: {
    type: Array,
    default: () => [
      // {
      //   value: "1",
      //   label: "Tag 1",
      // },
      // {
      //   value: "2",
      //   label: "Tag 2",
      // },
    ],
  },
});
const selectedTags = ref([]);
const toggleTag = (value) => {
  // 如果是多选，则选中
  if (props.isMultiple) {
    selectedTags.value = selectedTags.value.includes(value)
      ? selectedTags.value.filter((tag) => tag !== value)
      : [...selectedTags.value, value];
    if (props.hasAll) {
      handleToggleAll();
    }
  } else {
    selectedTags.value = [value];
  }
  emit("changeTag", selectedTags.value);
  emit("update:modelValue", selectedTags.value);
};
const handleToggleAll = () => {
  let allSelectedList = props.tagList.map((tag) => tag.value);
  if (selectedTags.value.length === allSelectedList.length) {
    isAllChecked.value = true;
    selectedTags.value = [];
  } else {
    isAllChecked.value = false;
  }
};
const isAllChecked = ref(true);
const toggleAll = () => {
  isAllChecked.value = !isAllChecked.value;
  if (isAllChecked.value) {
    selectedTags.value = [];
  }
};
watch(
  () => props.modelValue,
  (newVal) => {
    // 初始化
    selectedTags.value = newVal;
    if (props.hasAll && newVal.length === 0) {
      isAllChecked.value = true;
    }
  },
  { immediate: true, deep: true }
);
</script>
<style scoped>
.filter-tags {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}
.el-check-tag.is-disabled,
.el-check-tag.is-disabled:hover {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
}
</style>
